package net.tngou.jtdb.sql;


import net.tngou.jtdb.netty.TngouClient;

import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.PooledObjectFactory;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

public class DBManager {
	 static ObjectPool<TngouClient> pool = null;
	static  {
		PooledObjectFactory<TngouClient> factory = new DataSourcePoolableObjectFactory();
		GenericObjectPoolConfig config = new GenericObjectPoolConfig() ; 
		config.setLifo(false);
		config.setMaxIdle(5);
		config.setMinIdle(1);
		config.setMaxTotal(10);
		config.setMaxWaitMillis(5 * 1000);
		pool = new GenericObjectPool<TngouClient>(factory, config); 
	
	}

	
	
	public static TngouClient getConnection() {
		 try {
			 
			 if(pool==null)
			 {
				 PooledObjectFactory<TngouClient> factory = new DataSourcePoolableObjectFactory();
					GenericObjectPoolConfig config = new GenericObjectPoolConfig() ; 
					config.setLifo(false);
					config.setMaxIdle(5);
					config.setMinIdle(1);
					config.setMaxTotal(10);
					config.setMaxWaitMillis(5 * 1000);
					pool = new GenericObjectPool<TngouClient>(factory, config); 
			 }
			 
			 return pool.borrowObject();
					
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return null;
	}

	public static void closeConnection(TngouClient tngouClient) {
		
		try {
			
			 if(pool==null)
			 {
				 PooledObjectFactory<TngouClient> factory = new DataSourcePoolableObjectFactory();
				 GenericObjectPoolConfig config = new GenericObjectPoolConfig() ; 
					config.setLifo(false);
					config.setMaxIdle(5);
					config.setMinIdle(1);
					config.setMaxTotal(10);
					config.setMaxWaitMillis(5 * 1000);
					pool = new GenericObjectPool<TngouClient>(factory, config); 
			 }
			
			pool.returnObject(tngouClient);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
public static void close(TngouClient tngouClient) {
		
		try {
			tngouClient.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
